#!/usr/bin/python
"""
Removes Azureus torrents that have been seeded for awhile. Requires Dopal.
"""

import dopal.main

# Azureus host to connect to (XML-HTTP)
AZUREUS_HOST = 'mini'
# Share ratio required before removal
RATIO_LIMIT = 2000
# Number of hours of seeding required before removal
SEED_HOURS = 48
# Max seeds
MAX_SEEDS = 30

def _CmpShareRatio(download1, download2):
  return cmp(download1.stats.getShareRatio(), download2.stats.getShareRatio())

def _CmpSeedTime(download1, download2):
  return cmp(download1.stats.getSecondsOnlySeeding(), download2.stats.getSecondsOnlySeeding())
  
def _CmpCreationTime(download1, download2):
  return cmp(download1.getCreationTime(), download2.getCreationTime())

def RemoveTorrent(download):
  if not download.isComplete():
    return
  print ' removing %s' % (download,)
  try:
    download.stop()
  except dopal.errors.RemoteMethodError, s:
    if 'download already stopped' in str(s):
      pass
    else:
      raise
  # Remove torrent, keep files
  download.remove(True, False)

def GetDownloads(interface, sort_func=None):
  downloads = interface.getDownloadManager().getDownloads()
  if sort_func:
    return sorted(downloads, cmp=sort_func, reverse=True)
  return downloads

def RemoveHighShareRatioTorrents(interface):
  downloads = GetDownloads(interface, _CmpShareRatio)
  for download in downloads:
    ratio = download.stats.getShareRatio()
    hours_seeded = download.stats.getSecondsOnlySeeding() / 60 / 60
    print download, ratio, hours_seeded
    if ratio > RATIO_LIMIT and hours_seeded > SEED_HOURS:
      RemoveTorrent(download)

def RemoveErrorTorrents(interface):
  downloads = GetDownloads(interface)
  for download in downloads:
    status = download.stats.getTrackerStatus()
    # Error (torrent not registered with this tracker)
    if status.startswith('Error') and 'torrent not registered' in status:
      print '%s bad status %s' % (download, status)
      RemoveTorrent(download)

def RemoveStoppedTorrents(interface):
  downloads = GetDownloads(interface)
  for download in downloads:
    if download.getState() == download.ST_STOPPED:
      RemoveTorrent(download)

def LimitTorrents(interface):
  downloads = GetDownloads(interface, sort_func=_CmpCreationTime)
  downloads.reverse()
  for i in range(len(downloads) - MAX_SEEDS):
    RemoveTorrent(downloads[i])


if __name__ == '__main__':
  connection = dopal.main.make_connection(host=AZUREUS_HOST)
  interface = connection.getPluginInterface()

  RemoveHighShareRatioTorrents(interface)
  RemoveErrorTorrents(interface)
  RemoveStoppedTorrents(interface)
  LimitTorrents(interface)
